package com.hlt.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hlt.context.BaseContext;
import com.hlt.dto.LikesDTO;
import com.hlt.dto.LikesPageQueryDTO;
import com.hlt.dto.PostLikesPageQueryDTO;
import com.hlt.entity.Likes;
import com.hlt.entity.Posts;
import com.hlt.entity.Users;
import com.hlt.mapper.LikesMapper;
import com.hlt.mapper.PostsMapper;
import com.hlt.mapper.UsersMapper;
import com.hlt.result.PageResult;
import com.hlt.service.ILikesService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hlt.config.UserStatsUtils;
import com.hlt.vo.LikesVO;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.beans.factory.annotation.Autowired;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lzf
 * @since 2024-11-25
 */
@Service
public class LikesServiceImpl extends ServiceImpl<LikesMapper, Likes> implements ILikesService {

    @Autowired
    private PostsMapper postsMapper;

    @Autowired
    private UsersMapper usersMapper;

    @Autowired
    private UserStatsUtils userStatsUtils;

    @Override
    @Transactional
    public void addLike(LikesDTO likesDTO) {
        // 获取当前用户ID
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new IllegalArgumentException("请先登录");
        }

        // 参数校验
        Assert.notNull(likesDTO.getPostId(), "文章ID不能为空");

        // 检查文章是否存在
        Posts post = postsMapper.selectById(likesDTO.getPostId());
        if (post == null) {
            throw new IllegalArgumentException("文章不存在");
        }

        // 检查是否已点赞
        LambdaQueryWrapper<Likes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Likes::getUserId, Math.toIntExact(userId))
                .eq(Likes::getPostId, likesDTO.getPostId());
        if (count(queryWrapper) > 0) {
            throw new IllegalArgumentException("已经点赞过该文章");
        }

        // 创建点赞记录
        Likes like = new Likes();
        like.setUserId(Math.toIntExact(userId));
        like.setPostId(likesDTO.getPostId());
        like.setCreatedAt(LocalDateTime.now());

        // 保存点赞记录
        save(like);

        // 更新用户统计信息
        userStatsUtils.updateStats(Math.toIntExact(userId), "likedCount", true);

        // 更新文章点赞数量
        post.setLikesCount(post.getLikesCount() + 1);
        postsMapper.updateById(post);
    }

    @Override
    @Transactional
    public void removeLike(Integer postId) {
        // 获取当前用户ID
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new IllegalArgumentException("请先登录");
        }

        // 查询点赞记录
        LambdaQueryWrapper<Likes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Likes::getUserId, Math.toIntExact(userId))
                .eq(Likes::getPostId, postId);
        Likes like = getOne(queryWrapper);

        if (like == null) {
            throw new IllegalArgumentException("点赞记录不存在");
        }

        // 物理删除点赞记录
        removeById(like.getLikeId());

        // 更新用户统计信息
        userStatsUtils.updateStats(Math.toIntExact(userId), "likedCount", false);

        // 更新文章点赞数量
        Posts post = postsMapper.selectById(postId);
        post.setLikesCount(post.getLikesCount() - 1);
        postsMapper.updateById(post);
    }

    @Override
    public PageResult getUserLikes(LikesPageQueryDTO pageQueryDTO) {
        // 获取当前用户ID
        Long userId = BaseContext.getCurrentId();
        if (userId == null) {
            throw new IllegalArgumentException("请先登录");
        }

        // 构建分页对象
        Page<Likes> page = new Page<>(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Likes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Likes::getUserId, Math.toIntExact(userId))
                .orderByDesc(Likes::getCreatedAt);

        // 执行分页查询
        page = page(page, queryWrapper);

        // 获取所有文章ID
        List<Integer> postIds = page.getRecords().stream()
                .map(Likes::getPostId)
                .distinct()
                .collect(Collectors.toList());

        // 查询文章信息
        List<Posts> postsList = postsMapper.selectList(
                new LambdaQueryWrapper<Posts>().in(Posts::getPostId, postIds));
        Map<Integer, Posts> postMap = postsList.stream()
                .collect(Collectors.toMap(Posts::getPostId, post -> post));

        // 转换为VO对象
        List<LikesVO> likesVOList = page.getRecords().stream().map(like -> {
            LikesVO vo = new LikesVO();
            BeanUtils.copyProperties(like, vo);

            // 设置文章信息
            Posts post = postMap.get(like.getPostId());
            if (post != null) {
                vo.setTitle(post.getTitle());
            }

            return vo;
        }).collect(Collectors.toList());

        return new PageResult(page.getTotal(), likesVOList);
    }

    @Override
    public PageResult getPostLikes(PostLikesPageQueryDTO pageQueryDTO) {
        // 参数校验
        Assert.notNull(pageQueryDTO.getPostId(), "文章ID不能为空");

        // 检查文章是否存在
        Posts post = postsMapper.selectById(pageQueryDTO.getPostId());
        if (post == null) {
            throw new IllegalArgumentException("文章不存在");
        }

        // 构建分页对象
        Page<Likes> page = new Page<>(pageQueryDTO.getPageNum(), pageQueryDTO.getPageSize());

        // 构建查询条件
        LambdaQueryWrapper<Likes> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Likes::getPostId, pageQueryDTO.getPostId())
                .orderByDesc(Likes::getCreatedAt);

        // 执行分页查询
        page = page(page, queryWrapper);

        // 获取所有用户ID
        List<Integer> userIds = page.getRecords().stream()
                .map(Likes::getUserId)
                .distinct()
                .collect(Collectors.toList());

        // 查询用户信息
        List<Users> usersList = usersMapper.selectList(
                new LambdaQueryWrapper<Users>().in(Users::getUserId, userIds));
        Map<Integer, Users> userMap = usersList.stream()
                .collect(Collectors.toMap(Users::getUserId, user -> user));

        // 转换为VO对象
        List<LikesVO> likesVOList = page.getRecords().stream().map(like -> {
            LikesVO vo = new LikesVO();
            BeanUtils.copyProperties(like, vo);

            // 设置用户信息
            Users user = userMap.get(like.getUserId());
            if (user != null) {
                vo.setNickname(user.getNickName());
                vo.setAvatar(user.getAvatarUrl());
            }

            // 设置文章信息
            vo.setTitle(post.getTitle());

            return vo;
        }).collect(Collectors.toList());

        return new PageResult(page.getTotal(), likesVOList);
    }
}
